package com.lzh.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzh.eduservice.entity.EduSubject;
import com.lzh.eduservice.entity.ExcelSubjectData;
import com.lzh.eduservice.entity.subject.OneSubject;
import com.lzh.eduservice.entity.subject.TwoSubject;
import com.lzh.eduservice.listener.SubjectListener;
import com.lzh.eduservice.mapper.EduSubjectMapper;
import com.lzh.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzh.oss.servicebase.exceptionhandler.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author lzh
 * @since 2020-11-30
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file ,EduSubjectService subjectService) {

        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, ExcelSubjectData.class,new SubjectListener(subjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            throw new GuliException(20001,"添加课程分类失败");
        }
    }

    @Override
    public List<OneSubject> getAllSubject() {
        QueryWrapper<EduSubject> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id","0");
        List<EduSubject> oneSubjects = baseMapper.selectList(wrapperOne);

        QueryWrapper<EduSubject> wrapperTwo = new QueryWrapper<>();
        wrapperTwo.ne("parent_id","0");
        List<EduSubject> twoSubjects = baseMapper.selectList(wrapperTwo);

        List<OneSubject> finalSubject = new ArrayList<>();
        for (int i = 0; i < oneSubjects.size(); i++) {
            EduSubject eduSubject = oneSubjects.get(i);

            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(eduSubject,oneSubject);
            finalSubject.add(oneSubject);

            List<TwoSubject> twofinalSubject = new ArrayList<>();
            for (int m = 0; m < twoSubjects.size(); m++) {
                EduSubject subjectTwo = twoSubjects.get(m);
                if (subjectTwo.getParentId().equals(eduSubject.getId())) {
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(subjectTwo,twoSubject);
                    twofinalSubject.add(twoSubject);
                }
            }
           oneSubject.setChildren(twofinalSubject);
        }

        return finalSubject;
    }
}
